package tree;

/**
 * 9. 根据一棵树的前序遍历与中序遍历构造二叉树。
 * https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
 */
class Solution {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public int preIndex;
    public TreeNode buildTree(int[] preorder, int[] inorder) {


        TreeNode tree = buildTreeCreate(preorder,inorder,0,preorder.length - 1);
        return tree;
    }

    private TreeNode buildTreeCreate(int[] preorder,int[] inorder,int inbegin,int inend) {
        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[preIndex]);
        
        int rootIndex = findIndex(preorder,preorder[preIndex],inbegin,inend);
        if(rootIndex == -1) {
            return null;
        }
        preIndex++;
        root.left = buildTreeCreate(preorder ,inorder ,inbegin ,rootIndex - 1);
        root.right = buildTreeCreate(preorder ,inorder ,rootIndex + 1 ,inend);
        return root;
    }
    private int findIndex(int[] preorder,int rootIndex ,int inbegin ,int inend) {
        for(int i = inbegin;i <= inend;i++) {
            if(preorder[i] == rootIndex) {
                return i;
            }
        }
        return -1;
    }
}